from emmodels.em_basemodel import BaseModel
from emmysql.em_sqlmanager import engine, metaData
from sqlalchemy.schema import Table
import datetime
from sqlalchemy.sql import select
from emmongo import em_mongomanager as mongoManager

class BaseData(BaseModel):
    # _db_mapper = {
    #     'stkcode': 'code',
    #     'market': 'market',
    #     'stkname': 'name',
    #     'ipodate':'timeToMarket',
    #     'sys_cls':'sys_cls',
    #     'industry_zj': 'c_name',
    #     'concept_sina': 'c_name',
    #     'concept_tc':'concept_tc',
    #     'area': 'area',
    #     'create_time': 'create_time',
    #     'last_update_time': 'last_update_time'
    # }
    _db_mapper = {
        'code': 'stkcode',
        'market': 'market',
        'name': 'stkname',
        'ipodate': 'ipodate',
        'sys_cls': 'sys_cls',
        'industry': 'industry_zj',
        'c_name': 'concept_sina',
        'concept_tc': 'concept_tc',
        'area': 'area',
        'create_time': 'create_time',
        'last_update_time': 'last_update_time'
    }


    def __init__(self, stkcode=None, stkname=None, industry_zj='',ipodate='',sys_cls = '' ,concept_sina='', concept_tc='', area=None,
                 create_time=None, last_update_time=datetime.datetime.now().strftime('%Y-%m-%d'), **kwargs):
        self.set_up_with_db_mapper(**kwargs)
        if stkcode:
            self.stkcode = stkcode
        if stkname:
            self.stkname = stkname
        self.market = self.parse_market(self.stkcode)
        self.industry_zj = industry_zj
        self.sys_cls = sys_cls
        self.concept_sina = concept_sina
        self.concept_tc = concept_tc
        self.area = area
        self.create_time = create_time
        self.last_update_time = last_update_time
        self.ipodate = ipodate
        pass

    def parse_market(self, stk_code):
        # 这里做一部分过滤，200B股以及一些新上市的不加入到我们的池中
        if stk_code:
            # 730是上证的新股，深证的直接就是股票代码
            if stk_code[0:3] in ['601','600','603','900','730']:
                return 'SH'
            elif stk_code[0:3] in ['000','002','300']:
                return 'SZ'
        return ''

    def is_validate(self):
        return True if self.market else False

    # @classmethod
    # def insert_list(cls, data_list, **kwargs):
    #     if isinstance(data_list, list) :
    #         items =[item for item in data_list if (isinstance(item, BaseData) and item.is_validate())]
    #         connect = engine.connect()
    #         connect.execute(cls._table.insert(**kwargs), [item.to_dict() for item in items])

    # @classmethod
    # def select_stkcode(cls, stkcode):
    #     connect = engine.connect()
    #     rp = connect.execute(select([cls._table]).where(cls._table.c.stkcode == stkcode))
    #     return rp.first()


    # def sys_table(cls):
    #     pass

    def saveToMongo(self, tb_name=mongoManager.COL_BASE_DATA,filter=None, update=None):
        data = self.__dict__
        s_filter= filter or {'stk_code': self.stkcode}
        tmp = {}
        for k, v in data.items():
            # +self.__class__.__name__
            # jCache 是我专门用来缓存的数据 但是不想变成私有变量
            if not k.startswith('_') and not k.startswith('jCache_'):
                tmp[k] = v
        s_update = update or {'$set': tmp}
        mongoManager.db[tb_name].update_one(s_filter,s_update, upsert=True)

    @classmethod
    def select_all_from_mongo(cls, tb_name=mongoManager.COL_BASE_DATA):
        r = mongoManager.db[tb_name].find({})
        return r

    @classmethod
    def select_stk_from_mongo(cls, stk_code, tb_name=mongoManager.COL_BASE_DATA):
        r = mongoManager.db[tb_name].find_one({'stk_code':stk_code})
        return r

    def code_with_name(self):
        return '%s(%s)'%(self.stkcode, self.stkname)


# SelfFund.select_stk_from_mongo(stk_code='002241', tb_name=mongoManager.COL_SELF_FUND)


class ModuleData(object):
    # _db_mapper = {
    #     'code':'moduleid',
    #     'name':'module_name',
    #     'createtime':'create_time',
    #     'update_time':'update_time'
    # }
    # _table = Table('EM_MODULE_BASIC_DATA', metaData, autoload=True)
    # BaseModel.loadTable('EM_MODULE_BASIC_DATA', **_db_mapper)

    def __init__(self, module_code=None, module_name=None, module_stk_codes=None,
                 module_stk_names=None, module_stk_infos=None, source=None,
                 create_time=datetime.datetime.now().strftime('%Y-%m-%d'),
                 last_update_time=datetime.datetime.now().strftime('%Y-%m-%d'), **kwargs):
        self.module_code = module_code
        self.module_name = module_name
        self.module_stk_codes = module_stk_codes
        self.module_stk_names = module_stk_names
        self.module_stk_infos = module_stk_infos
        self.create_time = create_time
        self.last_update_time = last_update_time
        self.score = 0
        self.source = source
        self.score = 0
        self.up_count = 0
        self.p_count = 0
        self.down_count = 0
        self.total_count = 0
        self.zdf = 0
        self.top_zf_gu = ''
        self.top_df_gu = ''
        self.inamount = 0 #流入资金
        self.outamount = 0 #流出资金
        self.netamount = 0 #净流入资金
        self.netamout_pct = 0 #净流入率
        self.up_pct = 0 # 上涨家数占比
        self.set_with_dict(**kwargs)

    def set_with_dict(self,forceUpdate=False, **kwargs):
        for k, v in kwargs.items():
            if hasattr(self, k) and (not getattr(self, k) or forceUpdate):
               setattr(self, k, v)


    def saveToMongo(self):
        v = self.__dict__
        mongoManager.db[mongoManager.COL_MODULE_DATA].update_one({'module_code': self.module_code}, {'$set': v}, upsert=True)

    @classmethod
    def select_module(cls, module_code):
        r = mongoManager.db[mongoManager.COL_MODULE_DATA].find_one({'module_code':module_code})
        return r

    @classmethod
    def select_all_from_mongo(cls):
        r = mongoManager.db[mongoManager.COL_MODULE_DATA].find({})
        return r







